<?php
	require_once(dirname(__FILE__)."/../../inc/product_auth.php");
	include(dirname(__FILE__)."/../../../../../inc/class/proxy/BaseProxy.abstract.php");
	include("rsa.php");
	require_once(dirname(__FILE__)."/../../../../../inc/debug.php");	
class WFProxy extends ABaseProxy {
	/*
	protected $cgiArgs; // all cgi parameters are stored in this associative array
	protected $errCode; // for error checking
	protected $errMessage; // for error checking (Note: only for debug, not for UI)

	protected $httpObj; // easy http communication object
	protected $serverInfo; // use this object to retrieve server information
	*/
	private $m_output = array();
    private $m_incompatible = FALSE;

	// Proxy Init
	public function proxy_init() 
	{
		if (!isset($this->cgiArgs['serverid']))
		{
			$this->errCode = WF_PROXY_ERR_INIT_INVALID_INPUT;
			$this->errMessage = WF_PROXY_ERR_INIT_INVALID_INPUT_MSG;
		}
	}

	// Proxy Exec
	public function proxy_exec() 
	{
		// localhost, directly launch report.php
		if ($this->cgiArgs['serverid'] == '1')
		{
            if($this->cgiArgs['type'] == "WR"){
                $cmd = "php ../php/lwcs_report.php ";
                $this->AddParam($cmd, "t");
                $this->AddParam($cmd, "tr");
                $this->AddParam($cmd, "ds");
                $this->AddParam($cmd, "m");
                $this->AddParam($cmd, "C");
                exec($cmd, $this->m_output, $error);
                if ($error != 0)
                {
                    $this->errCode = WF_PROXY_ERR_EXEC_OTHERS;
                    $this->errMessage = "exec lwcs_report.php failed. err = $error";
                }
            }
            else{        
                $cmd = "php ../php/report.php ";
                $this->AddParam($cmd, "T");
                $this->AddParam($cmd, "D");
                $this->AddParam($cmd, "IP");
                $this->AddParam($cmd, "M");
                $this->AddParam($cmd, "TOP");
                $this->AddParam($cmd, "C");
                $this->AddParam($cmd, "CONSOLE_LANG");
                exec($cmd, $this->m_output, $error);
                if ($error != 0)
                {
                    $this->errCode = WF_PROXY_ERR_EXEC_OTHERS;
                    $this->errMessage = "exec report.php failed. err = $error";
                }
            }
		}
		else
		{
			// Have we already login?
			$mySessionInfo = $this->LoadSessionInfo();
			if( $mySessionInfo != null )
			{
				/*
				 * there are stored session info, to see does it work.
				 */
				// 1. we need sid and cookie
				if( isset($mySessionInfo['sid']) && isset($mySessionInfo['cookie']) ) {
					// 2. set cookie
					$this->httpObj->setCookieStr($mySessionInfo['cookie']);
					// 3. send the request to report.php directly
					if( !$this->RetriveData($mySessionInfo['sid']) )
					{ 
						$this->errCode = WF_PROXY_ERR_EXEC_CONNECT;
						$this->errMessage = $this->httpObj->getErrMessage();
					}
					if( $this->httpObj->getCode() == 200 ) {
						// yes, we did.
						return;
					}
                    else if ( $this->httpObj->getCode() == 404 ) {
                        $this->incompatible = TRUE;
                        return;
                    }
				}
			}

			// login
			if (!$this->Login($sid))
			{
				return;
			} 
			
			// retrive data
			if (!$this->RetriveData($sid))
			{ 
				$this->errCode = WF_PROXY_ERR_EXEC_CONNECT;
				$this->errMessage = $this->httpObj->getErrMessage();
			}
            if ( $this->httpObj->getCode() == 404 ) {
                $this->incompatible = TRUE;
            }
		}
	}

	// Proxy Result
	public function proxy_output() 
	{
		header('Content-type: application/xml;charset=utf-8');

        if ($this->incompatible === TRUE)
        {
            echo json_encode(array('incompatible' => 1));
            return;
        }
		
		if ($this->cgiArgs['serverid'] == '1')		// local
		{
			foreach ($this->m_output as $value)
			{
				

				

			}
				
		} 
		else
		{ 
			mydebug_log("[modTMCSS] echo body:".$this->httpObj->getBody());
			echo $this->httpObj->getBody();
			
		}
		
		$value = '<ActiveUser xmlns="http://www.trendmicro.com/tmcss"><day date="1302278400" U="1"></day><day date="1302364800" U="2"></day><day date="1302451200" U="0"></day><day date="1302537600" U="0"></day><day date="1302624000" U="0"></day><day date="1302710400" U="0"></day><day date="1302796800" U="0"></day></ActiveUser>';
		mydebug_log("[modTMCSS] echo value:".$value);			
		echo $value;
		
	}

	// Proxy Check
	public function proxy_check()
	{  
		if ($this->cgiArgs['serverid'] == '1')		// local 
			return TRUE;
		else 
		{
			// Have we already login?
			$mySessionInfo = $this->LoadSessionInfo();
			if( $mySessionInfo != null )
			{
				/*
				 * there are stored session info, to see does it work.
				 */
				// 1. we need sid and cookie
				if( isset($mySessionInfo['sid']) && isset($mySessionInfo['cookie']) ) {
					// 2. set cookie
					$this->httpObj->setCookieStr($mySessionInfo['cookie']);
					// 3. send the request to index2.php?sid=
					$URL = "/php/index2.php?sid=".$mySessionInfo['sid'];
					$this->httpObj->setPath($URL);
					$this->httpObj->setMethod_GET();
					if( $this->httpObj->Send() == TRUE ) {
						if( $this->httpObj->getCode() == 200 ) {
							// yes, we did.
							return TRUE;
						}
					}
				}
			}
			// oh, we need to relogin
			return $this->Login($sid);
		}
	}

	private function AddParam(&$cmd, $param)
	{
		if (isset($this->cgiArgs[$param]))
		{
			$cmd = $cmd.$param."=".$this->cgiArgs[$param]." ";
		}
	}
	
	private function AddURLParam(&$URL, $param)
	{
		if (isset($this->cgiArgs[$param]))
		{
			$URL = $URL.$param."=".$this->cgiArgs[$param]."&";
		}
	}
	
	private function Login(&$sid)
	{
		$tarray = array(); 

		// make sure the path
		$this->httpObj->setPath('/');

		// Get root page
		if( $this->httpObj->Send() == FALSE ) {
			$this->errCode = WF_PROXY_ERR_EXEC_CONNECT;
			$this->errMessage = WF_PROXY_ERR_EXEC_CONNECT_MSG.": ".$this->httpObj->getErrMessage();
			return FALSE;
		}

		// Get cookie
		$tarray = $this->httpObj->getCookies();
		
		// Parse index.php
		$htmldom = new DOMDocument();
		if (!@$htmldom->loadHTML($this->httpObj->getBody()))
		{ 
			$this->errCode = WF_PROXY_ERR_EXEC_CONNECT;
			$this->errMessage = WF_PROXY_ERR_EXEC_CONNECT_MSG;
			return FALSE;
		}

		// We need 3 variables: pubkey, nonce, and sid
		if (($htmldom->getElementById("pubkey") == NULL) || 
			($htmldom->getElementById("nonce")  == NULL) ||
			($htmldom->getElementById("sid") == NULL))
		{
			$this->errCode = WF_PROXY_ERR_EXEC_LOGIN;
			$this->errMessage = WF_PROXY_ERR_EXEC_LOGIN_MSG."(".__FILE__ . ":" . __LINE__.")";
			return FALSE;
		}
		
		$pubkey = $htmldom->getElementById("pubkey")->getAttribute("value");
		$nonce = $htmldom->getElementById("nonce")->getAttribute("value");
		$sid = $htmldom->getElementById("sid")->getAttribute("value");
		
		$enc_txt = $this->serverInfo['username']."\t".$this->serverInfo['password']."\t".$nonce;
		
		$bignum = gmp_init($pubkey,16);
		$pubkey_dec = gmp_strval($bignum,10);
		$cipher = base64_encode(rsa_encrypt($enc_txt, "65537", $pubkey_dec, 4096));
		
		$this->httpObj->setPath("/auth.php");
		$this->httpObj->setMethod_POST();
	
		$this->httpObj->setCGI( "nonce", $nonce);
		$this->httpObj->setCGI( "data", $cipher);
		$this->httpObj->setCGI( "sid", $sid);
		$this->httpObj->setCookies($tarray);
	
		// send auth request
		if( $this->httpObj->Send() == FALSE ) {
			$this->errCode = WF_PROXY_ERR_EXEC_CONNECT;
			$this->errMessage = WF_PROXY_ERR_EXEC_CONNECT_MSG.": ".$this->httpObj->getErrMessage();
			return FALSE;
		}
		
		$headerArr = $this->httpObj->getHeaders() ;
		
		// Login Success 
		if (($this->httpObj->getCode() == 302) &&
			(isset($headerArr["Location"])) &&
			(strpos($headerArr["Location"], "index2.php?sid=") !== FALSE))
		{
			// store session info for next request
			$this->SaveLoginInfo($sid, $this->httpObj->getCookieStr());
			return TRUE;
		}
		// Login Failed
		else										
		{ 
			$this->errCode = WF_PROXY_ERR_EXEC_LOGIN;
			$this->errMessage = WF_PROXY_ERR_EXEC_LOGIN_MSG."(".__FILE__ . ":" . __LINE__.")";
			return FALSE;
		}
/*		
		echo "\n\n";
		$tarray = $this->httpObj->getHeaders();
		print_r($tarray);
		echo "<h1>Body</h1><BR>\n";
		echo $this->httpObj->getBody();
*/ 
	}

	private function RetriveData($sid)
	{
        if($this->cgiArgs['type'] == "WR"){
            $URL = "/php/lwcs_report.php?sid=".$sid."&";
            $this->AddURLParam($URL, "t");
            $this->AddURLParam($URL, "tr");
            $this->AddURLParam($URL, "ds");
            $this->AddURLParam($URL, "m");
            $this->AddURLParam($URL, "C");
            $this->AddURLParam($URL, "CONSOLE_LANG");
            
            $this->httpObj->setPath($URL); 
            $this->httpObj->setMethod_GET();
            if( $this->httpObj->Send() == FALSE ) {
                $this->errCode = WF_PROXY_ERR_EXEC_CONNECT;
                $this->errMessage = WF_PROXY_ERR_EXEC_CONNECT_MSG.": ".$this->httpObj->getErrMessage();
                return FALSE;
            }
            return TRUE;
        }
        else{
            $URL = "/php/report.php?sid=".$sid."&";
            $this->AddURLParam($URL, "T");
            $this->AddURLParam($URL, "D");
            $this->AddURLParam($URL, "IP");
            $this->AddURLParam($URL, "M");
            $this->AddURLParam($URL, "TOP");
            $this->AddURLParam($URL, "C");
            $this->AddURLParam($URL, "CONSOLE_LANG");
            
            $this->httpObj->setPath($URL); 
            $this->httpObj->setMethod_GET();
            if( $this->httpObj->Send() == FALSE ) {
                $this->errCode = WF_PROXY_ERR_EXEC_CONNECT;
                $this->errMessage = WF_PROXY_ERR_EXEC_CONNECT_MSG.": ".$this->httpObj->getErrMessage();
                return FALSE;
            }
            return TRUE;
        }
	}

	private function ServerKey()
	{
		return $this->serverInfo['protocol'].$this->serverInfo['username'].$this->serverInfo['password'].$this->serverInfo['host'].$this->serverInfo['port'];
	}

	private function LoadSessionInfo()
	{
		$key = $this->ServerKey();
		if( $this->session_info != null && isset($this->session_info[$key]) ) {
			return $this->session_info[$key];
		}
		return null;
	}

	private function SaveLoginInfo($sid, $cookie)
	{
		$key = $this->ServerKey();
		$sinfo = array();
		$sinfo['sid'] = $sid;
		$sinfo['cookie'] = $cookie;
		$this->session_info[$key] = $sinfo;
		$this->save_sinfo();
	}
}
